/*
    Created by IntelliJ IDEA.
    @Auther: gaozhe
    @Date: 2020/4/22 上午 9:05
    
*/
package gaozhe;

import javax.print.DocFlavor;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

public class MusicDownload {
    public static void main(String[] args) {
        System.out.printf("请输入网易云歌曲的http链接: ");
        String httpUrl = new Scanner(System.in).next();
        String songID = getSongID(httpUrl);
        System.out.println("获取ID："+songID);
        System.out.println("获取歌曲链接："+getMusicUrl(songID));
        String musicUrl = getMusicUrl(songID);
        download(musicUrl);

    }

    //根据http链接获取歌曲id
    public static String getSongID(String httpUrl){
        int beginIndex = httpUrl.indexOf("=");
        int lastIndex = httpUrl.indexOf("&");
        return httpUrl.substring(beginIndex+1, lastIndex);
    }
    //根据id获取歌曲的链接
    public static String getMusicUrl(String songID){
        return "https://music.163.com/song/media/outer/url?id="+songID+".mp3";
    }


    //开始下载
    public static void download(String msg){
        HttpURLConnection connection = null;

        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;


        try {
            String location = new URL(msg).openConnection().getHeaderField(("Location"));
            System.out.println("获取歌曲重定向："+location);
            System.out.println("解析完成，开始下载...");
            connection = (HttpURLConnection) new URL(location).openConnection();
            inputStream = connection.getInputStream();



            //获取文件名
            //String fileName = url.getFile().substring(Integer.parseInt(String.valueOf(url.getFile().toString().lastIndexOf("/"))));
            String fileName = msg.substring(msg.indexOf("=")+1);

            //创建新文件
            fileOutputStream = new FileOutputStream(new File("C:\\Users\\111\\Desktop\\"+fileName));
            byte[] buffer = new byte[1024];
            int len;
            while ((len=inputStream.read(buffer))!=-1){
                //写数据
                fileOutputStream.write(buffer,0,len);
            }
        } catch (Exception e) {
            System.err.println("您输入的http地址不正确！");
            e.printStackTrace();
        }finally {
            if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection !=null){
                connection.disconnect();
            }
            System.out.printf("歌曲下载完成！");
        }
    }
}
